//
//  SchNoticeViewController.swift
//  EduManage
//
//  Created by design02 on 16/12/7.
//  Copyright © 2016年 wsl. All rights reserved.
//

import UIKit

class SchNoticeViewController: BaseViewController, UITableViewDelegate, UITableViewDataSource {
    
    var segmentedControl: UISegmentedControl!
    var tableView: UITableView!
    
    var mark = "1"
    
    var workArray = NSMutableArray()
    var classArray = NSMutableArray()
    
    let top = 10
    var pageIndex = 1
    
    var modetype: String!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Do any additional setup after loading the view.
        self.title = "全校通知"
        
        //1207 - 铃铛管家去除右上角发送通知按钮
        #if EDUMANAGE || HSEDUMANAGE || TXEDUMANAGE || HYEDUMANAGE
        
        self.navigationItem.rightBarButtonItem = UIBarButtonItem.init(image: UIImage.init(named: "add"), style: UIBarButtonItemStyle.plain, target: self, action: #selector(SchNoticeViewController.addclick))
        #endif
        
        InitViews()
        
        NotificationCenter.default.addObserver(self, selector: #selector(SchNoticeViewController().refresh), name: NSNotification.Name(rawValue: "SchNoticeSendSuccessful"), object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(SchNoticeViewController().deleSchNotice), name: NSNotification.Name(rawValue: "SchNoticeDelegateNotification"), object: nil)

    }
    
    func deleSchNotice() {
        let alert = UIAlertController.init(title: "温馨提示", message: "您是否确认删除该条全校通知，删除后不可恢复！请慎重！", preferredStyle: UIAlertControllerStyle.alert)
        let deleAction = UIAlertAction.init(title: "删除", style: UIAlertActionStyle.default) { (alert) in
            //删除全校通知 操作
            
        }
        let cancelAction = UIAlertAction.init(title: "取消", style: UIAlertActionStyle.cancel, handler: nil)
        
        alert.addAction(deleAction)
        alert.addAction(cancelAction)
        self.navigationController?.present(alert, animated: true, completion: { 
            //呈现弹出框
        })
        
    }
    
    func InitViews(){
        
        tableView = UITableView.init(frame: self.view.frame)
        tableView.backgroundColor = UIColor.init(hexString: "f6f6f6", alpha: 1)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.separatorStyle = UITableViewCellSeparatorStyle.none
        self.view.addSubview(tableView)
        setUpRefresh()
        
    }
    
    func setUpRefresh() {
        
        tableView.header = MJRefreshNormalHeader.init(refreshingTarget: self, refreshingAction: #selector(SchNoticeViewController.refresh))
        tableView.footer = MJRefreshAutoNormalFooter.init(refreshingTarget: self, refreshingAction: #selector(SchNoticeViewController.loadMore))
//        tableView.footer.isAutomaticallyChangeAlpha = true
        self.tableView.header.beginRefreshing()
    }
    /**
     加载更多
     */
    func loadMore() {
        
        if (reachability?.isReachable())! {
            let user = getUserPojo()
            let url = server + adminwebapppi
            pageIndex += 1
            let page: String = String(pageIndex)
            let request = requestHeader + "8</t><sch>" + user.schid + "</sch><top>5</top><pagindex>" + page + "</pagindex></channel></rss>"
            
            let tempArray = getData(url, request: request) as [AnyObject]
            print("\(tempArray)")
            
            for i in 0...tempArray.count-1 {
                let tempDic = tempArray[i] as! JSON
                let type = tempDic["types"].stringValue
                
                //type = 7 说明是校级通知
                if type == "7" {
                    workArray.add(tempArray[i])
                }
            }
//        workArray.addObjects(from: getData(url, request: request) as [AnyObject])
            
            tableView.reloadData()
            
        } else {
            HYLog("网络连接：不可用")
        }

        tableView.footer.endRefreshing()
    }
    /**
     刷新数据
     t=8   全校班级通知
     XmlNode schseridxml = ndoc.SelectSingleNode("//rss/channel/sch");
     XmlNode topxml = ndoc.SelectSingleNode("//rss/channel/top");
     XmlNode pagcountxml = ndoc.SelectSingleNode("//rss/channel/pagindex");
     */
    func refresh() {
        
        if (reachability?.isReachable())! {
            let user = getUserPojo()
            pageIndex = 1
            let page: String = String(pageIndex)
            
            let url = server + "/webapp/apps/ad_Announcement.ashx"
            let request = requestHeader +  "3</t><schid>" + user.schid + "</schid><top>10</top><pageindex>" + page + "</pageindex></channel></rss>"
            
//            #if EDUMANAGE || HSEDUMANAGE || TXEDUMANAGE || HYEDUMANAGE
//            #else
//                let url = server + adminwebapppi
//                let request = requestHeader + "8</t><sch>" + user.schid + "</sch><top>5</top><pagindex>" + page + "</pagindex></channel></rss>"
//
//            #endif
            
            
            workArray = getData(url, request: request)
            
            if workArray.count == 0 {
                TSMessage.showNotification(in: self, title: "温馨提示", subtitle: "暂时还没有全校通知、请添加后重试！", image: nil, type: TSMessageNotificationType.warning, duration: 2.0, callback: nil, buttonTitle: "知道了", buttonCallback: nil, at: TSMessageNotificationPosition.top, canBeDismissedByUser: true)
                
            }else {
                tableView.separatorStyle = UITableViewCellSeparatorStyle.none
                tableView.reloadData()
            }
            
        } else {
            HYLog("网络连接：不可用")
        }

        tableView.header.endRefreshing()
    }

    //MARK: - uitable view delegate and datasource
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 130
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return workArray.count
        
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        if (indexPath as NSIndexPath).row < workArray.count {
            let cellIdentifier = "NoticeTableViewCellIdentifier";
            let dic = workArray[indexPath.row] as! JSON
            let cell = NoticeTableViewCell(dictionary: dic, reuseIdentifier: cellIdentifier)
            cell.selectionStyle = UITableViewCellSelectionStyle.none;
            return cell
        }else {
            return UITableViewCell()
        }
        
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        let dic = workArray[indexPath.row] as! JSON
        let contentVC = EditSchNoticeViewController()
        contentVC.dic = dic
        self.navigationController?.pushViewController(contentVC, animated: true)
        
    }
    
    //MARK: - 跳转到发送通知
    func addclick(){
        let add = AddnoticeViewController()
        add.modetype = modetype
        self.navigationController?.pushViewController(add, animated: true)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
    /*
     // MARK: - Navigation
     
     // In a storyboard-based application, you will often want to do a little preparation before navigation
     override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
     // Get the new view controller using segue.destinationViewController.
     // Pass the selected object to the new view controller.
     }
     */

}
